
// request请求
import Request from "@/utils/request"
// 接口api
import Api from "@/utils/api"
// 消息提示
import msgT from "@/utils/msg"
// 小程序解密


// 小程序获取openid
function getOpenId() {
	uni.login({
		success: (res) => {
			Request.get(Api.getOpenId, {
				appid: uni.getStorageSync('appid'),
				// secret: '10031c7c83680cdd56da469a271c9b86',
				secret: getApp().globalData.secret,
				js_code: res.code,
				grant_type: 'authorization_code'
			}).then(
				(res) => {
					uni.setStorageSync('openid', res.openid);
					uni.setStorageSync('session_key', res.session_key);
					msgT.toast(res.openid)
				},
				(err) => {
					msgT.error(err)
				}
			)
		},
		fail: (err) => {
			msgT.error(err)
		}
	});
}

// 小程序获取手机号
function getPhoneNumber(e) {
	console.log(e,'eeee')
	if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
		console.log('用户拒绝提供手机号');
	} else {
		console.log('用户同意提供手机号',uni.getStorageSync('appid'),uni.getStorageSync('session_key'),e);
		let pc = new WXBizDataCrypt(uni.getStorageSync('appid'), uni.getStorageSync('session_key'));
		let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
		// console.log('jiemi---', data.phoneNumber)
		return data.phoneNumber
	}
}

// 获取用户信息(含用户头像/昵称)
function getUser() {
	return new Promise((resolve, reject) => {
		uni.getUserProfile({
			desc: '用户登录',
			success: res => {
				// console.log('getUser', res) // 用户的信息
				this.avatarUrl = res.userInfo.avatarUrl //微信头像
				this.nickName = res.userInfo.nickName // 微信昵称
				// console.log('-------pp', res.userInfo)
				resolve(res.userInfo)
			},
			fail: (err) => {
				msgT.error(err)
			}
		})
	})
}
//  url地址
function convertObj(data) {
    var _result = [];
    for (var key in data) {
		if(key != 'pageIndex' && key !='pageNum' && key !='pageSize'){
			var value = data[key];
			if (Array.isArray[value]) {
			  value.forEach(function(_value) {
				_result.push(key + "=" + _value);
			  });
			} else {
			  _result.push(key + '=' + value);
			}
		}
    
    }
    return _result.join('&');
  }


// 获取URL参数
function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
	var context = "";
	if (r != null)
		context = decodeURIComponent(r[2]);
	reg = null;
	r = null;
	return context == null || context == "" || context == "undefined" ? "" : context;
}

// 微信支付
function payOrder(params) {
	var a = new Promise((resolve, aa) => {
	  Request.post(Api.payOrder, params,'application/json;charset=utf-8','accessToken').then(
		(res) => {
			if (res.code == '0000') {
				let pay = res.data;
				uni.requestPayment({
					appId:pay.appId,
					provider: "wxpay", 				//服务提供商
					timeStamp: pay.timeStamp,		//时间戳
					nonceStr: pay.nonceStr,			//随机字符串
					package: pay.packageValue,		//统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=xx
					signType: pay.signType,			//签名算法
					paySign: pay.paySign,			//签名
					// 支付成功的回调
				
					success(result) {
						console.log(result,'result')
						if (result.errMsg == "requestPayment:ok") {
							resolve('1')
							msgT.success('购买成功')
						}
					},
					// 支付失败回调
					fail(err) {
						uni.showToast({
							title: '支付失败',
							durarion: 2000,
							success: () => {
								
							}
						})
						resolve('2')
					
						msgT.error('支付失败')
					}
				})
			}
		},
		(err) => {
			msgT.error(err)
		        })	
    })	
     return a ;
}

module.exports = {
	getOpenId,
	getPhoneNumber,
	getUser,
	GetQueryString,
	payOrder,
	convertObj
}
